/* 感测项目设定 */
import React, { useEffect, useMemo, useState } from 'react';
import { connect } from 'umi';
import {
  Space,
  Row,
  Col,
  Button,
  Table,
  notification,
  Modal,
  Form,
  Input,
  Select,
} from 'antd';
import { selectOption } from './SettingGlobal';
import { sensorSetListAll, sensorSetAdd, sensorSetUpdate } from './setServers';

const grabType = [
  { name: 'crawl', value: 'crawl' },
  { name: 'cal', value: 'cal' },
];

/* 编辑 添加 */
const SensorModal = (props: any) => {
  const [modalForm] = Form.useForm();
  const { modalVisible, modalDatas, modalOnOk, closeVisible } = props;

  console.log('modalDatas', modalDatas);

  const modalOk = async () => {
    const formData = await modalForm.validateFields();
    const params = {
      devicetype: modalDatas['DEVICETYPE'],
      itemdesc: formData['ITEMDESC'],
      itemname: formData['ITEMNAME'],
      processtype: formData['PROCESSTYPE'],
      unit: formData['UNIT'],
    };
    console.log('params ????', params);
    if (modalDatas['MY__TYPE'] === 'ADD') {
      sensorSetAdd(params).then((res) => {
        // console.log('添加是否成功', res);
        notification.success({
          message: '添加结果！',
          description: res.message || '添加成功！',
        });
        modalOnOk();
      });
    } else {
      modalForm.validateFields().then(() => {
        // console.log('获取表单的数据', res, modalDatas);
        sensorSetUpdate({ itemid: modalDatas['ITEMID'], ...params })
          .then((res) => {
            notification.success({
              message: '修改结果！',
              description: res.message || '修改成功！',
            });
            modalOnOk();
          })
          .catch((rej) => {
            notification.success({
              message: '修改结果！',
              description: rej.message || '修改失败！',
            });
          });
      });
    }
  };

  useEffect(() => {
    if (!modalDatas) {
      modalForm.resetFields();
    } else {
      modalForm.setFieldsValue(modalDatas);
    }
  }, []);

  return (
    <Modal
      title={modalDatas['MY__TYPE'] === 'ADD' ? modalDatas['title'] : '编辑'}
      maskClosable={false}
      visible={modalVisible}
      width={800}
      onOk={modalOk}
      onCancel={() => {
        modalForm.resetFields();
        closeVisible();
      }}
    >
      <Form
        form={modalForm}
        name="modalForm"
        labelCol={{ span: 8 }}
        autoCapitalize="off"
        autoComplete="off"
        // initialValues={{
        //   ...modalDatas
        // }}
      >
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item label="感测器项目" name="ITEMNAME">
              <Input />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="感测项目名称" name="ITEMDESC">
              <Input />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item label="单位" name="UNIT">
              <Input />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="抓取方式" name="PROCESSTYPE">
              <Select>{selectOption(grabType, 'value', 'name')}</Select>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

/* 感测项目设定 */
const SensorItemMtn = (props: any) => {
  const { history, match, location } = props;

  const [tabDataSource, settabDataSource] = useState([]);
  const [modalVisible, setmodalVisible] = useState(false);
  const [modalDatas, setModalDatas] = useState({});

  // 获取全部的数据
  const getTableSource = (params: { deviceType: string }) => {
    sensorSetListAll(params).then((res) => {
      console.log('感测项目设定', res);
      res && settabDataSource(res['data']);
    });
  };

  const modalOnOk = () => {
    setmodalVisible(false);
    getTableSource(match.params);
  };
  const closeVisible = () => {
    setmodalVisible(false);
  };

  useEffect(() => {
    getTableSource(match.params);
  }, []);

  const tabColumns = [
    // {
    //   title: '序号',
    //   render: (_: any, record: any, index: any) => {
    //     return index
    //   }
    // },
    {
      title: '感测项目',
      dataIndex: 'ITEMNAME',
      key: 'ITEMNAME',
    },
    {
      title: '感测项目名称',
      dataIndex: 'ITEMDESC',
      key: 'ITEMDESC',
    },
    {
      title: '单位',
      dataIndex: 'UNIT',
      key: 'UNIT',
    },
    {
      title: '抓取方式',
      dataIndex: 'PROCESSTYPE',
      key: 'PROCESSTYPE',
    },
    {
      title: '处理',
      render: (record: any) => {
        return (
          <Button
            size="small"
            type="primary"
            onClick={() => {
              setModalDatas(record);
              setmodalVisible(true);
            }}
          >
            编辑
          </Button>
        );
      },
    },
  ];

  const sensorModal = useMemo(() => {
    return (
      <SensorModal
        modalVisible={modalVisible}
        modalOnOk={modalOnOk}
        closeVisible={closeVisible}
        modalDatas={modalDatas}
      />
    );
  }, [modalVisible]);

  return (
    <div>
      <Row gutter={16 + 8 * 2} align="middle">
        <Col span={20}>
          <Space direction="vertical">
            <h2>感测项目设定</h2>
            <h3>
              {location['state']
                ? location['state']['typename']
                : '缺少 typename'}
            </h3>
            <Button
              type="primary"
              onClick={() => {
                setModalDatas({
                  MY__TYPE: 'ADD',
                  title: '添加',
                  DEVICETYPE: match.params['deviceType'],
                });
                setmodalVisible(true);
              }}
            >
              新增
            </Button>
          </Space>
        </Col>
        <Col span={4}>
          <Button
            type="primary"
            ghost
            onClick={() => history.push('/sensorTypeSet')}
          >
            返回 感測器類別設定
          </Button>
        </Col>
      </Row>
      <Table
        rowKey={(record: any) => record['itemid'] || Math.random().toString(16)}
        size="small"
        columns={tabColumns}
        dataSource={tabDataSource}
        pagination={false}
      />
      {modalVisible && sensorModal}
    </div>
  );
};

export default SensorItemMtn;
